﻿

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Threading.Tasks;
using Castle.Core.Internal;
using CoreCms.Net.Auth.HttpContextUser;
using CoreCms.Net.Configuration;
using CoreCms.Net.IRepository;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.DTO;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Services;
using CoreCms.Net.Utility.Helper;
using Essensoft.Paylink.Alipay.Domain;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Nito.AsyncEx;
using Org.BouncyCastle.Asn1.X9;
using SqlSugar;
using SqlSugar.Extensions;

namespace CoreCms.Net.Web.WebApi.Controllers
{
    /// <summary>
    /// 产品
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private IHttpContextUser _user;
        private readonly AsyncLock _mutex = new AsyncLock();

        private IXcrProductsServices _xcrProductsServices;
        private IXcrProductsTypeServices _xcrProductsTypeServices;
        private ICoreCmsAreaServices _coreCmsAreaServices;
        private IXrcOrderServices _xrcOrderServices;
        private ICoreCmsUserWeChatInfoServices _coreCmsUserWeChatInfoServices;
        private readonly ICoreCmsMessageCenterServices _messageCenterServices;

        private ICoreCmsUserServices _coreCmsUserServices;
        private ICoreCmsLabelServices _coreCmsLabelServices;
        private ICoreCmsLabelRepository _coreCmsLabelRepository;
        private IXrcAdminServices _xrcAdminServices;
        private IXrcOtherServices _xrcOtherServices;
        private IXrcOtherTypeServices _xrcOtherTypeServices;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="user"></param>
        /// <param name="xcrProductsServices"></param>
        /// <param name="xcrProductsTypeServices"></param>
        public ProductsController(IHttpContextUser user, IXcrProductsServices xcrProductsServices,
            IXcrProductsTypeServices xcrProductsTypeServices, ICoreCmsAreaServices coreCmsAreaServices,
            IXrcOrderServices xrcOrderServices, ICoreCmsUserWeChatInfoServices coreCmsUserWeChatInfoServices,
            ICoreCmsUserServices coreCmsUserServices, ICoreCmsLabelServices coreCmsLabelServices,
            ICoreCmsLabelRepository coreCmsLabelRepository, ICoreCmsMessageCenterServices messageCenterServices,
            IXrcAdminServices xrcAdminServices, IXrcOtherServices xrcOtherServices, IXrcOtherTypeServices xrcOtherTypeServices

            )
        {
            _user = user;
            _xcrProductsServices = xcrProductsServices;
            _xcrProductsTypeServices = xcrProductsTypeServices;
            _coreCmsAreaServices = coreCmsAreaServices;
            _xrcOrderServices = xrcOrderServices;
            _coreCmsUserWeChatInfoServices = coreCmsUserWeChatInfoServices;
            _coreCmsUserServices = coreCmsUserServices;
            _coreCmsLabelServices = coreCmsLabelServices;
            _coreCmsLabelRepository = coreCmsLabelRepository;
            _messageCenterServices = messageCenterServices;
            _xrcAdminServices = xrcAdminServices;
            _xrcOtherServices = xrcOtherServices;
            _xrcOtherTypeServices = xrcOtherTypeServices;

        }



        /// <summary>
        ///     获取区域信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<WebApiCallBack> GetArea()
        {
            var jm = new WebApiCallBack();


            var ids = new List<PostAreasTreeNode>();
            var areaTrees = await _coreCmsAreaServices.GetTreeArea(ids, 0, 2, 0);

            jm.status = true;
            jm.data = areaTrees;
            jm.msg = ids.Count.ToString();

            return jm;
        }

        #region 产品分类列表
        /// <summary>
        /// 产品分类列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> TypeList([FromBody] FMPageByIntId entity)
        {
            var jm = new WebApiCallBack();

            Expression<Func<XcrProductsType, bool>> where = m => m.delete == 0 && m.state == 1;


            int storeId = entity.store > 0 ? entity.store : _user.Store > 0 ? _user.Store : 1;
            where = where.And(p => p.gid == storeId);

            var list = await _xcrProductsTypeServices.QueryPageAsync(where, p => p.create_time, OrderByType.Desc,
                entity.page, entity.limit);
            jm.status = true;
            jm.data = list;
            return jm;

        }
        #endregion
        #region 产品列表
        /// <summary>
        /// 产品列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> NoticeList([FromBody] FMProducts entity)
        {
            var jm = new WebApiCallBack();


            Expression<Func<XcrProducts, bool>> where = m => m.isDel == false && m.isMarketable == true;
            int storeId = entity.store > 0 ? entity.store : _user.Store > 0 ? _user.Store : 1;
            where = where.And(p => p.gid == storeId);

            if (entity.typeid > 0)
            {
                where = where.And(p => p.goodsTypeId == entity.typeid);
            }
            if (!string.IsNullOrEmpty(entity.area))
            {
                var areas = entity.area.Split(',');
                var area = "";
                if (areas.Length == 1)
                {
                    area = areas[0].ToString();
                    where = where.And(p => p.area.Contains(area));
                }
                else if (areas.Length == 2)
                {
                    area = areas[1].ToString();
                    where = where.And(p => p.area == area);
                }
            }

            if (!string.IsNullOrEmpty(entity.title))
            {
                where = where.And(p => p.name.Contains(entity.title));
            }
            if (entity.money > 0)
            {
                switch (entity.money)
                {
                    case 1:
                        where = where.And(p => p.money > 0 && p.money <= 500000);
                        break;
                    case 2:
                        where = where.And(p => p.money >= 500000 && p.money <= 1000000);
                        break;
                    case 3:
                        where = where.And(p => p.money >= 1000000 && p.money <= 2000000);
                        break;
                    case 4:
                        where = where.And(p => p.money >= 2000000 && p.money <= 5000000);
                        break;
                    case 5:
                        where = where.And(p => p.money >= 5000000);
                        break;
                }
            }

            var list = await _xcrProductsServices.QueryPageAsync(where, p => p.sort, OrderByType.Desc,
                entity.page, entity.limit);

            List<ProductsDto> dtolist = list.Select(p => new ProductsDto
            {
                id = p.id,

                area = p.area,
                isDel = p.isDel,
                bn = p.bn,
                brief = p.brief,
                buyCount = p.buyCount,
                name = p.name,
                image = p.image,
                images = p.images,
                goodsCategoryId = p.goodsCategoryId,
                goodsTypeId = p.goodsTypeId,
                isMarketable = p.isMarketable,
                intro = p.intro,
                spesDesc = p.spesDesc,
                commentsCount = p.commentsCount,
                viewCount = p.viewCount,
                createTime = p.createTime,
                sort = p.sort,
                labelIds = p.labelIds,
                newSpec = p.newSpec,
                updateTime = p.updateTime,
                isRecommend = p.isRecommend,
                isHot = p.isHot,
                productsDistributionType = p.productsDistributionType,
                money = p.money.ToString(),
                rate = p.rate
            }).ToList();

            for (int i = 0; i < dtolist.Count; i++)
            {

                dtolist[i].money = ReportsHelper.toNumber(Convert.ToInt32(dtolist[i].money));
                dtolist[i].rate = dtolist[i].rate + "%";
                if (!string.IsNullOrEmpty(dtolist[i].labelIds))
                {
                    int[] ids = dtolist[i].labelIds.Split(',').Select(s => int.Parse(s)).ToArray();
                    var items = await _coreCmsLabelServices.QueryListByClauseAsync(p => ids.Contains(p.id));
                    var idsInts = items.Select(p => p.name).ToArray();
                    dtolist[i].labelIds = String.Join(",", idsInts);
                }
            }
            jm.status = true;
            jm.data = dtolist;
            return jm;
        }

        #endregion

        /// <summary>
        /// 获取单个产品内容
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> NoticeInfo([FromBody] FMIntId entity)
        {
            var jm = new WebApiCallBack();

            var model = await _xcrProductsServices.QueryByIdAsync(entity.id);

            if (model == null)
            {
                jm.msg = "数据获取失败";
                return jm;
            }
            else
            {
                ProductsDto products = ReportsHelper.Map<XcrProducts, ProductsDto>(model);
                products.rate = model.rate + "%";
                products.money = ReportsHelper.toNumber(Convert.ToInt32(model.money));
                int[] ids = products.labelIds.Split(',').Select(s => int.Parse(s)).ToArray();
                var items = await _coreCmsLabelServices.QueryListByClauseAsync(p => ids.Contains(p.id));
                var idsInts = items.Select(p => p.name).ToArray();
                products.labelIds = String.Join(",", idsInts);
                jm.status = true;
                jm.data = products;
                return jm;
            }

        }




        #region  申请贷款=========================================================

        /// <summary>
        /// 申请贷款
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> CreateOrder([FromBody] FMOrder entity)
        {

            var jm = new WebApiCallBack();
            if (entity.ProId >= 0)
            {
                using (await _mutex.LockAsync())
                {
                    var order = await _xrcOrderServices.QueryByClauseAsync(p => p.UserId == _user.ID && p.ProId == entity.ProId && p.AddTime.Month == DateTime.Now.Month && p.AddTime.Day == DateTime.Now.Day);
                    if (order == null)
                    {
                        order = new XrcOrder();
                        order.AddTime = DateTime.Now;
                        order.UserId = _user.ID;
                        order.Remark = entity.Remark;
                        order.BrokerId = entity.BrokerId > 0 ? UserHelper.GetUserIdByShareCode(entity.BrokerId) : 0;
                        order.Name = entity.Name;
                        order.Mobile = entity.Mobile;
                        order.ExpQuota = entity.ExpQuota;
                        order.Gid = entity.Gid;
                        if (entity.ProId >= 1)
                        {
                            var products = _xcrProductsServices.QueryById(entity.ProId);
                            if (products != null)
                            {
                                order.ProId = products.id;
                                order.ProName = products.name;
                                order.ProType = products.goodsTypeId;
                            }
                            else
                            {
                                jm.msg = "未查询到产品信息";
                                jm.status = false;
                                return jm;
                            }
                        }
                        else
                        {
                            order.ProId = 0;
                            order.ProName = "测额度";
                            order.ProType = 0;
                        }
                        int add = await _xrcOrderServices.InsertAsync(order);
                        if (add > 0)
                        {
                            order.Id = add;
                            await _coreCmsUserServices.UpdateAsync(p => new CoreCmsUser() { realName = order.Name, mobile = order.Mobile }, p => p.id == _user.ID);


                            jm.msg = "申请成功,等待审核";
                            jm.status = true;
                            // 如果有经纪人给经纪人发送通知
                            if (order.BrokerId > 0)
                            {
                                await _messageCenterServices.SendMessage(order.BrokerId.ObjToInt(), GlobalEnumVars.PlatformMessageTypes.CreateOrder.ToString(), JObject.FromObject(order));
                            }
                            var admins = await _xrcAdminServices.QueryListByClauseAsync(p => p.state == 1 && p.gid == entity.Gid);
                            if (admins.Count > 0)
                            {
                                var userids = admins.Select(p => p.userid).ToArray();
                                if (userids.Length > 0)
                                {
                                    for (int i = 0; i < userids.Length; i++)
                                    {
                                        if (userids[i] > 0)
                                            await _messageCenterServices.SendMessage(userids[i], GlobalEnumVars.PlatformMessageTypes.CreateOrder.ToString(), JObject.FromObject(order));
                                    }
                                }
                            }
                        }
                        else
                        {
                            jm.msg = "申请失败,联系客服";
                            jm.status = false;
                        }
                    }
                    else
                    {
                        jm.msg = "今日已提交申请";
                        jm.status = false;
                    }
                }

            }
            else
            {
                jm.msg = "未查询到产品编号";
                jm.status = false;
            }
            return jm;
        }
        #endregion

        #region 业务分类列表
        /// <summary>
        /// 业务分类列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiCallBack> OtherTypeList([FromBody] FMPageByIntId entity)
        {
            var jm = new WebApiCallBack();

            Expression<Func<XrcOtherType, bool>> where = m => m.delete == 0;
            int storeId = entity.store > 0 ? entity.store : _user.Store > 0 ? _user.Store : 1;
            where = where.And(p => p.gid == storeId);

            var list = await _xrcOtherTypeServices.QueryPageAsync(where, p => p.sort, OrderByType.Desc,
                entity.page, entity.limit);
            jm.status = true;
            jm.data = list;
            return jm;

        }
        #endregion
        #region  其他业务咨询=========================================================
        /// <summary>
        /// 其他业务咨询
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<WebApiCallBack> CreateOther([FromBody] FMOther entity)
        {

            var jm = new WebApiCallBack();

            using (await _mutex.LockAsync())
            {
                var order = await _xrcOtherServices.QueryByClauseAsync(p => p.UserId == _user.ID && p.Type_Id == entity.Type_Id && p.Create_Time.Month == DateTime.Now.Month && p.Create_Time.Day == DateTime.Now.Day);
                if (order == null)
                {
                    order = new XrcOther();
                    order.Create_Time = DateTime.Now;
                    order.UserId = _user.ID;
                    order.Results = "";
                    order.Content = entity.Content;
                    order.Name = entity.Name;
                    order.Mobile = entity.Mobile;
                    order.Gid = entity.Gid;
                    if (entity.Type_Id > 0)
                    {
                        var products = _xrcOtherTypeServices.QueryById(entity.Type_Id);
                        if (products != null)
                        {
                            order.Type_Id = products.id;
                            order.Type_Name = products.type_name;
                        }
                        else
                        {
                            jm.msg = "未查询到业务信息";
                            jm.status = false;
                            return jm;
                        }
                    }

                    int add = await _xrcOtherServices.InsertAsync(order);
                    if (add > 0)
                    {
                        order.Id = add;
                        await _coreCmsUserServices.UpdateAsync(p => new CoreCmsUser() { realName = order.Name, mobile = order.Mobile }, p => p.id == _user.ID);


                        jm.msg = "提交成功,等待处理联系";
                        jm.status = true;

                        var admins = await _xrcAdminServices.QueryListByClauseAsync(p => p.state == 1 && p.gid == entity.Gid);
                        if (admins.Count > 0)
                        {
                            var userids = admins.Select(p => p.userid).ToArray();
                            if (userids.Length > 0)
                            {
                                for (int i = 0; i < userids.Length; i++)
                                {
                                    if (userids[i] > 0)
                                        await _messageCenterServices.SendMessage(userids[i], GlobalEnumVars.PlatformMessageTypes.CreateOrder.ToString(), JObject.FromObject(order));
                                }
                            }
                        }
                    }
                    else
                    {
                        jm.msg = "提交失败,联系客服";
                        jm.status = false;
                    }
                }
                else
                {
                    jm.msg = "今日已提交改业务申请，请明日再提交";
                    jm.status = false;
                }
            }
            return jm;
        }
        #endregion

    }
}
